﻿using d1Common;
using d1Common.WebController;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Filters;

namespace d1Project.App_Start
{
    public class WebApiErrorAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext filterContext)
        {
            //使用log4net或其他记录错误消息
            Exception _error = filterContext.Exception;
            if (_error is UserException)
            {
                UserException _webApiExcetpion = _error as UserException;
                filterContext.Response = new HttpResponseMessage(_webApiExcetpion.HttpStatusCode);
            }
            else if (_error is AggregateException)
            {
                //do nothing
                return;
            }
            else
            {
                doServices.Instance.DoLog.Error("", "发现未知错误", _error);
                filterContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }

            filterContext.Response.Content = new StringContent(_error.Message);
        }
    }
}